﻿function loadExistingItems() {
  var sites = chrome.extension.getBackgroundPage().localStorage;
  var always = [];
  var never = [];
  var assumed = [];
  for (var site in sites) {
    if (site[0] == "_") {
      continue;
    }
    if (sites[site] == "true") {
      always.push(site);
    } else if (sites[site] == "false") {
      never.push(site);
    } else if (sites[site] == "defaultfalse") {
      assumed.push(site);
    }
  }
  always.sort();
  never.sort();
  assumed.sort();
  document.getElementById("newAlways").value = always.join("\n");
  document.getElementById("newNever").value = never.join("\n");
  document.getElementById("newAssumed").value = assumed.join("\n");
  var shouldCacheMisses = sites["__shouldCacheMisses"] == "true";
  document.getElementById("shouldCacheMisses").checked = shouldCacheMisses;
  var shouldCacheMisses = sites["__shouldCreateRulesInIncognito"] == "true";
  document.getElementById("shouldCreateRulesInIncognito").checked = shouldCacheMisses;
}

function saveChanges() {
  var updateMessageVersion = localStorage["__updateMessage"];
  chrome.extension.getBackgroundPage().localStorage.clear();
  var shouldCreateRulesInIncognito = document.getElementById("shouldCreateRulesInIncognito").checked ? "true" : "false";
  chrome.extension.getBackgroundPage().localStorage["__shouldCreateRulesInIncognito"] = shouldCreateRulesInIncognito;
  var shouldCacheMisses = document.getElementById("shouldCacheMisses").checked ? "true" : "false";
  chrome.extension.getBackgroundPage().localStorage["__shouldCacheMisses"] = shouldCacheMisses;
  addEntriesToList(document.getElementById("newAlways"), "true");
  addEntriesToList(document.getElementById("newNever"), "false");
  if (shouldCacheMisses) {
    addEntriesToList(document.getElementById("newAssumed"), "defaultfalse");
  }
  localStorage["__updateMessage"] = updateMessageVersion;
  loadExistingItems();
}

function addEntriesToList(newEntriesElt, val) {
  var sites = chrome.extension.getBackgroundPage().localStorage;
  var urls = newEntriesElt.value.split("\n");
  for (var i in urls) {
    if (urls[i] != "") {
      sites[urls[i]] = val;
    }
  }
}